<template>
  <form @submit.prevent="submitForm">
    <div>
      <label for="name">姓名：</label>
      <input type="text" id="name" v-model="formData.name" required>
    </div>
    <div>
      <label for="age">年龄：</label>
      <input type="number" id="age" v-model="formData.age" required min="1">
    </div>
    <div>
      <label>性别：</label>
      <label><input type="radio" v-model="formData.gender" value="男" required> 男</label>
      <label><input type="radio" v-model="formData.gender" value="女"> 女</label>
    </div>
    <div>
      <label for="grade">年级：</label>
      <select id="grade" v-model="formData.grade" required>
        <option value="">请选择</option>
        <option value="大一">大一</option>
        <option value="大二">大二</option>
        <option value="大三">大三</option>
        <option value="大四">大四</option>
      </select>
    </div>
    <button type="submit">{{ isEditing ? '更新' : '添加' }}</button>
    <button type="button" @click="cancel">取消</button>
  </form>
</template>

<script>
export default {
  props: {
    student: Object
  },
  emits: ['submit', 'cancel'],
  data() {
    return {
      formData: {
        id: null,
        name: '',
        age: '',
        gender: '',
        grade: ''
      },
      isEditing: false
    }
  },
  watch: {
    student: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.formData = { ...newVal };
          this.isEditing = true;
        } else {
          this.resetForm();
          this.isEditing = false;
        }
      }
    }
  },
  methods: {
    submitForm() {
      this.$emit('submit', { ...this.formData });
      this.resetForm();
    },
    cancel() {
      this.$emit('cancel');
      this.resetForm();
    },
    resetForm() {
      this.formData = {
        id: null,
        name: '',
        age: '',
        gender: '',
        grade: ''
      };
      this.isEditing = false;
    }
  }
}
</script>

<style scoped>
form > div {
  margin-bottom: 15px;
}
label {
  display: inline-block;
  width: 60px;
}
input, select {
  padding: 5px;
  width: 200px;
}
button {
  margin-right: 10px;
  padding: 5px 15px;
}
</style>